package com.humble.vichatbackend.controller;

import com.humble.vichatbackend.exception.BusinessException;
import com.humble.vichatbackend.model.enums.ErrorCode;
import com.humble.vichatbackend.service.ChatService;
import com.humble.vichatbackend.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RestController;

@RestController
@ServerEndpoint("/chat/{teamId}/{id}")
public class ChatController {
    //websocket端点是一个连接一个端点对象，所以服务类使用静态对象
    private static ChatService chatService;

    @Autowired
    public void setChatService(ChatService chatService) {
        ChatController.chatService = chatService;
    }

    public ChatController() {}

    @OnOpen
    public void onOpen(Session session, @PathParam("id") Long id,@PathParam("teamId") Long teamId) {
        chatService.connect(id,teamId,session);
    }

    @OnMessage
    public void onMessage(@PathParam("id") Long id, @PathParam("teamId") Long teamId, String message) {
        chatService.sendMessage(id,teamId,message);
    }

    @OnClose
    public void onClose(@PathParam("id") Long id, @PathParam("teamId") Long teamId) {
        chatService.closeConnection(id,teamId);
    }
}
